/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package Tools;

import java.util.Arrays;
import java.util.List;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;

/**
 *
 * @author Иван
 */
public class CMDThreadGUI implements Runnable {

    public Thread t;
    private List<String> parsedInputData;
    private TModel model;
    private ACommand command;
    private Logger logger;
    private String usersCommand;
    private IObserverGUI observer;

    public CMDThreadGUI(String usersCommand, IObserverGUI observer) {
        this.observer = observer;
        this.usersCommand = usersCommand;
        logger = Logger.getLogger(CMDThread.class);
        t = new Thread(this, "CommandThread");
        t.start();
    }

    
    @Override
    public void run() {
        try {
            model = TModel.getInstance();

            parsedInputData = model.parsingInputData(usersCommand);
            
            logger.info("<command>" + usersCommand + "<command>");

            command = model.getInitCommandFactory().initializeCommand(parsedInputData);
            command.setParameters(parsedInputData);
            command.action(null);

            logger.info("command is complete");
           
            String[] results = command.getPrintResult().split("\n");

            observer.updateView(command.commandName, Arrays.asList(results));
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            
            //link on parent component
            JOptionPane.showConfirmDialog(null, ex.getMessage(), "Error", JOptionPane.OK_OPTION, JOptionPane.ERROR_MESSAGE);
        }
    }
}
